<!DOCTYPE html>
<!--
Copyright 2012 The Closure Library Authors. All Rights Reserved.

Use of this source code is governed by the Apache License, Version 2.0.
See the COPYING file for details.
-->
<html>
<head>
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <!--

  Author: dbk@google.com (David Barrett-Kahn)
  -->
  <title>Closure Unit Tests - goog.testing.events</title>
  <script src="../../base.js"></script>
  <script>
    goog.require('goog.net.NetworkStatusMonitor');
    goog.require('goog.testing.events.EventObserver');
    goog.require('goog.testing.events.OnlineHandler');
    goog.require('goog.testing.jsunit');
  </script>
</head>
<body>
<script>
  var handler;

  var observer;

  function tearDown() {
    handler = null;
    observer = null;
  }

  function testInitialValue() {
    createHandler(true);
    assertEquals(true, handler.isOnline());
    createHandler(false);
    assertEquals(false, handler.isOnline());
  }

  function testStateChange() {
    createHandler(true);
    assertEventCounts(0 /* expectedOnlineEvents */,
        0 /* expectedOfflineEvents */);

    // Expect no events.
    handler.setOnline(true);
    assertEquals(true, handler.isOnline());
    assertEventCounts(0 /* expectedOnlineEvents */,
        0 /* expectedOfflineEvents */);

    // Expect one offline event.
    handler.setOnline(false);
    assertEquals(false, handler.isOnline());
    assertEventCounts(0 /* expectedOnlineEvents */,
        1 /* expectedOfflineEvents */);

    // Expect no events.
    handler.setOnline(false);
    assertEquals(false, handler.isOnline());
    assertEventCounts(0 /* expectedOnlineEvents */,
        1 /* expectedOfflineEvents */);

    // Expect one online event.
    handler.setOnline(true);
    assertEquals(true, handler.isOnline());
    assertEventCounts(1 /* expectedOnlineEvents */,
        1 /* expectedOfflineEvents */);
  }

  function createHandler(initialValue) {
    handler = new goog.testing.events.OnlineHandler(initialValue);
    observer = new goog.testing.events.EventObserver();
    goog.events.listen(handler,
       [goog.net.NetworkStatusMonitor.EventType.ONLINE,
           goog.net.NetworkStatusMonitor.EventType.OFFLINE],
       observer);
  }

  function assertEventCounts(expectedOnlineEvents, expectedOfflineEvents) {
    assertEquals(expectedOnlineEvents, observer.getEvents(
            goog.net.NetworkStatusMonitor.EventType.ONLINE).length);
    assertEquals(expectedOfflineEvents, observer.getEvents(
            goog.net.NetworkStatusMonitor.EventType.OFFLINE).length);
  }
</script>
</body>
</html>
